<template>
  <div style="display: flex">
    <div style="margin-top: 10px">
      <!-- 搜索框 -->
      <div>
        <span>搜索地址：</span>
        <el-autocomplete
          v-model="keywords"
          style="width: 300px"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
        <!-- 显示经纬度和地址 -->
        <span style="margin-left: 10px">
          <span>经度：{{ form.lng }}</span>
          <span style="margin-left: 10px">纬度：{{ form.lat }}</span>
          <span>地址：{{ form.address }}</span>
        </span>
        <!-- 清空按钮 -->
        <el-button
          style="margin-left: 10px"
          type="danger"
          size="small"
          @click="reset"
          >清空</el-button
        >
        <!-- 获取当前位置按钮 -->
        <el-button
          style="margin-left: 10px"
          type="primary"
          size="small"
          @click="getCurrentLocation"
          >获取当前位置</el-button
        >
      </div>
      <!-- 地图容器 -->
      <div id="container" class="container"></div>
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-content">
          <div>
            <div>
              <!-- 充电站统计 -->
              <el-card :body-style="{ padding: '30px' }">
                <div
                  style="
                    width: 100%;
                    height: 120px;
                    display: flex;
                    justify-content: space-between;
                  "
                >
                  <el-col :span="13" style="display: flex">
                    <div class="icon-text" @click="gochargerList">
                      <svg
                        t="1727315714077"
                        class="icon"
                        viewBox="0 0 1024 1024"
                        version="1.1"
                        xmlns="http://www.w3.org/2000/svg"
                        p-id="5337"
                        width="50"
                        height="50"
                      >
                        <path
                          d="M493.215185 324.980364H168.234822a33.978182 33.978182 0 1 1 0-67.956364h324.980363a33.978182 33.978182 0 1 1 0 67.956364z m272.011637 681.006545H35.906095a35.002182 35.002182 0 1 1 0-70.004364h729.320727a35.002182 35.002182 0 1 1 0 70.004364z m114.501818-74.007273c-55.994182 0-101.469091-44.450909-101.469091-99.095272v-285.789091a30.021818 30.021818 0 0 1 59.950546 0v285.789091c0 21.597091 18.618182 39.098182 41.518545 39.098181s41.518545-17.501091 41.518545-39.098181V331.869091c-7.168-11.729455-20.712727-33.978182-29.463272-48.500364l-2.420364-3.909818-97.838545-161.885091a30.021818 30.021818 0 1 1 51.386181-30.999273l97.792 161.885091 2.327273 3.863273 33.652364 55.296 4.561454 7.307636v518.05091c0 54.597818-45.568 99.048727-101.515636 99.048727z"
                          fill="#2F96FF"
                          p-id="5338"
                        ></path>
                        <path
                          d="M705.229731 670.999273h-60.043636V427.008c0-49.058909 43.287273-88.994909 96.535272-88.994909 53.201455 0 96.488727 39.936 96.488728 88.994909v128.977455H778.213004V427.008c0-15.732364-16.709818-28.997818-36.491637-28.997818-19.781818 0-36.491636 13.265455-36.491636 28.997818v243.991273zM148.220276 37.981091h160.023273v904.005818H148.220276V37.981091z m617.006546 253.021091a24.017455 24.017455 0 0 1-1.024-47.988364l152.808727-6.795636a24.017455 24.017455 0 0 1 2.141091 48.034909l-152.855273 6.749091h-1.070545z m-199.540364 266.193454l-96.535273 4.375273 19.176728-133.957818L378.853004 615.796364l92.718545-2.141091-30.068364 124.462545 124.229819-180.922182z"
                          fill="#2F96FF"
                          p-id="5339"
                        ></path>
                        <path
                          d="M710.25664 974.987636h-70.050909V94.999273a24.994909 24.994909 0 0 0-24.994909-24.994909H175.21664a24.994909 24.994909 0 0 0-24.994909 24.994909v879.988363H80.217367V94.999273A95.092364 95.092364 0 0 1 175.21664 0h439.994182a95.092364 95.092364 0 0 1 94.999273 94.999273v879.988363z"
                          fill="#2F96FF"
                          p-id="5340"
                        ></path>
                      </svg>
                      <span>充电站</span>
                    </div>
                    <span class="text">{{ chargingstation.num }}个</span>
                  </el-col>
                  <!-- 充电桩统计 -->
                  <el-col :span="13" style="display: flex">
                    <div class="icon-text">
                      <svg
                        t="1727316290766"
                        class="icon"
                        viewBox="0 0 1024 1024"
                        version="1.1"
                        xmlns="http://www.w3.org/2000/svg"
                        p-id="12673"
                        width="50"
                        height="50"
                      >
                        <path
                          d="M748.34 905.04l168.69-166.55-104.54-0.64 1.63-101.97L667 798.22h99.33zM192.61 312.2c11.56 22.92 117.85 172.72 150.16 218.09a35.364 35.364 0 0 0 28.81 14.86h0.09a35.336 35.336 0 0 0 28.83-15.02c32.2-45.74 138.09-196.63 148.96-217.56 14.28-27.48 22.13-59.48 22.13-90.1 0-110.54-89.94-200.46-200.46-200.46s-200.46 89.92-200.46 200.46c0 30.6 7.37 60.77 21.93 89.69 0.01 0.02 0.01 0.03 0.01 0.04zM371.14 92.76c71.51 0 129.71 58.19 129.71 129.71 0 19.2-5.16 40.15-14.12 57.42-6.17 11.42-59.7 89.11-115.32 168.53-51.06-72.24-108.91-155.31-115.64-168.1-9.51-18.95-14.35-38.42-14.35-57.84 0.01-71.53 58.21-129.72 129.72-129.72z"
                          fill="#1296db"
                          p-id="12674"
                        ></path>
                        <path
                          d="M312.19 222.52c0 32.56 26.4 58.96 58.96 58.96s58.96-26.4 58.96-58.96-26.4-58.96-58.96-58.96-58.96 26.4-58.96 58.96zM535.19 497.44l160.23 49.32v25.38a222.987 222.987 0 0 1 47.17-16.79v-6.15l188.67-32.83v81.41c31.21 24.49 55.84 57.01 70.75 94.42V128.18c0-10.47-4.63-20.4-12.67-27.12-7.99-6.71-18.61-9.56-28.9-7.7l-256.45 45.62-65.5-21.78c-18.68-6.22-38.58 3.87-44.75 22.41-6.15 18.54 3.87 38.56 22.41 44.73l74.02 24.61c1.72 0.57 3.48 0.99 5.25 1.29v287.17l-146.36-45.05c-12.46-3.82-25.63 3.18-29.48 15.59-3.82 12.46 3.15 25.66 15.61 29.49z m207.4-293.47l188.67-33.56v298.07l-188.67 32.84V203.97z m-174.3 603.16l-179.46-50.41V623.44c0-13.02-10.55-23.58-23.58-23.58-13.04 0-23.58 10.56-23.58 23.58v133.88l-235.84 37.01V128.18c0-19.54-15.85-35.38-35.38-35.38s-35.38 15.83-35.38 35.38v707.51c0 10.34 4.51 20.16 12.39 26.89 7.85 6.71 18.29 9.71 28.47 8.06L369 824.65l228.44 64.16c-14.72-24.78-24.86-52.42-29.15-81.68z"
                          fill="#1296db"
                          p-id="12675"
                        ></path>
                        <path
                          d="M792.01 1001.65c-122.55 0-226.03-103.51-226.03-226s103.48-226 226.03-226c124.6 0 225.96 101.4 225.96 226 0.01 122.48-103.47 226-225.96 226z m0-409.66c-103.02 0-183.66 80.71-183.66 183.76 0 102.99 80.64 183.66 183.66 183.66s183.66-80.71 183.66-183.76c0-102.98-80.64-183.66-183.66-183.66z"
                          fill="#1296db"
                          p-id="12676"
                        ></path>
                      </svg>
                      <span>充电桩</span>
                    </div>
                    <span class="text">{{ chargingstation.count }}个</span>
                  </el-col>
                </div>
              </el-card>
            </div>
          </div>
          <!-- 充电站列表展示 -->
           <div>
            <!-- 搜索 -->
             <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="充电站名称">
                <el-input v-model="s" placeholder="请输入充电站名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="findAll()">查询</el-button>
              </el-form-item>
             </el-form>
           </div>
          <div class="sidebar-list" style="overflow-y: auto;">
            <el-col  :span="24">
              <el-table :data="tableData" style="width: 100%"  @row-click="handleRowClick">
                <el-table-column label="图片" width="80px">
                 <!-- 图片 -->
                  <template slot-scope="scope">
                    <el-image
                      :src="scope.row.image"
                      style="width: 40px; height: 40px"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="充电站名称" width="100px">
                </el-table-column>
                <el-table-column
                  prop="carNum"
                  label="汽车充电桩数"
                  width="150px"
                >
                </el-table-column>
                <el-table-column
                  prop="batteryNum"
                  label="电瓶车充电桩数"
                  width="150px"
                >
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="地址"
                  width="150px"
                >
                </el-table-column>
              </el-table>
            </el-col>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader"; // 导入高德地图API加载器
import axios from "axios";


// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: "2ec2a397ebfc994bc9e70a41d0f9a0f7",
};

export default {
  name: "HomeView",
  data() {
    return {
      s:'',
      // 充电站列表数据
      tableData: [
      
      ],
      // 充电站个数
      chargingstation: {  },
      // 其他数据...
      watchId: null, // 用于存储 watchPosition 的 ID
      map: null, // 地图实例
      marker: "", // 标记点
      geoCoder: null, // 地址逆解析
      AutoComplete: null, // 搜索提示
      ToolBar: null, // 缩放控件
      HawkEye: null, // 地图放大镜
      keywords: "", // 搜索关键字
      form: {
        // 位置信息
        lng: "119.793098",
        lat: "31.91243",
        address: "",
      },
      loading: false, // 搜索节流阀
      options: [], // 搜索提示信息
    };
  },
  created() {
    this.initMap(); // 初始化地图
  },
  methods: {
    // 前往充电站页面
    gochargerList(){
      this.$router.push({
					path: '/chargingStationList'
				})
    },
    // 统计充电站和充电桩数量
    countNum(){
      axios.get("/bdc/bdc/getChargingStationNum").then(res=>{
        this.chargingstation = res.data
      })
    },
    // 加载充电站数据
    findAll(){
      console.log(this.s);
      axios.get("/bdc/bdc/getChargingStation?name="+this.s).then(res=>{
        this.tableData = res.data
      })
    },
    // 充电站部分
    handleRowClick(row) {
      // 当点击一行时，调用 search 方法并传入 name 属性
      this.search(row);
      this.keywords = row.address;
      console.log('点击了行：', this.keywords);
      
       // 调用搜索框的方法
    this.querySearchAsync(row.address, (results) => {
      if (results.length > 0) {
        const selectedResult = results[0]; // 选择第一个搜索结果
        this.handleSelect(selectedResult);
      }
    });

    },
    search(row) {
      // 这里是你的搜索逻辑
      console.log('搜索:', row);
    },
    // 地图部分
    getCurrentLocation() {
      if (navigator.geolocation) {
        this.watchId = navigator.geolocation.watchPosition(
          (position) => {
            // 成功获取位置
            this.form.lng = position.coords.longitude;
            this.form.lat = position.coords.latitude;
            this.removeMarker(); // 清除旧的标记点
            this.setMapMarker(); // 设置新的标记点
            // 一旦获取到位置信息，停止监听
            this.stopWatchingLocation();
          },
          (error) => {
            // 获取位置失败
            switch (error.code) {
              case error.PERMISSION_DENIED:
                console.error("用户拒绝了位置请求。");
                break;
              case error.POSITION_UNAVAILABLE:
                console.error("位置信息不可用。请检查设备的GPS和网络连接。");
                break;
              case error.TIMEOUT:
                console.error("获取位置超时。请检查设备的GPS和网络连接。");
                break;
              case error.UNKNOWN_ERROR:
                console.error("未知错误。");
                break;
            }
            // 停止监听
            this.stopWatchingLocation();
          },
          {
            enableHighAccuracy: true, // 是否请求高精度位置
            timeout: 10000, // 增加超时时间到10秒
            maximumAge: 0, // 最大缓存时间，设置为0表示每次都请求新的位置数据
          }
        );
      } else {
        // 浏览器不支持 Geolocation
        alert("您的浏览器不支持地理位置功能。");
      }
    },

    stopWatchingLocation() {
      if (this.watchId) {
        navigator.geolocation.clearWatch(this.watchId);
        this.watchId = null;
      }
    },
    reset() {
      this.keywords = ""; // 清空搜索关键词
      this.form = {
        // 重置位置信息
        lng: "119.793098",
        lat: "31.91243",
        address: "",
      };
      this.removeMarker(); // 清除标记点
      this.setMapMarker(); // 设置新的标记点
    },
    initMap() {
      AMapLoader.load({
        key: "58fbec5fd4946bf942e47c0a71dd836c", // 高德地图API Key
        version: "2.0",
        plugins: [
          "AMap.Geocoder",
          "AMap.AutoComplete",
          "AMap.ToolBar",
          "AMap.HawkEye",
        ], // 加载插件
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            // 创建地图实例
            viewMode: "3D",
            zoom: 23,
            center: [this.form.lng, this.form.lat],
          });
          this.geoCoder = new AMap.Geocoder({
            // 地址逆解析插件
            city: "010",
            radius: 1000,
          });
          this.AutoComplete = new AMap.AutoComplete({ city: "全国" }); // 搜索提示插件
          // this.ToolBar = new AMap.ToolBar({
          //   // 缩放控件
          //   position: { bottom: "210px", right: "35px" },
          // });
          this.HawkEye = new AMap.HawkEye({
            // 地图放大镜
            position: { bottom: "110px", left: "35px" },
          });
          this.map.addControl(this.ToolBar); // 添加缩放控件到地图
          //      this.map.addControl(this.HawkEye); // 添加地图放大镜到地图
          this.removeMarker(); // 清除标记点
          this.setMapMarker(); // 设置标记点
          this.map.on("click", (e) => {
            // 监听地图点击事件
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            this.removeMarker();
            this.setMapMarker();
          });
        })
        .catch((err) => {
          // 处理错误
          console.error(err);
        });
    },
    setMapMarker() {
      this.map.setFitView(); // 自动调整视图
      this.marker = new AMap.Marker({
        // 创建标记点
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.toGeoCoder(); // 逆解析地址
      this.map.setFitView();
      this.map.add(this.marker); // 将标记点添加到地图
    },
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker); // 移除标记点
      }
    },
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        // 逆解析地址
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress; // 设置地址
        } else {
          this.form.address = "";
        }
      });
    },
    querySearchAsync(queryString, cb) {
      if (queryString) {
        this.AutoComplete.search(queryString, (status, result) => {
          // 搜索地点
          if (status === "complete") {
            this.options = result.tips.map((item) => ({
              ...item,
              value: item.name,
            })); // 处理搜索结果
          } else {
            this.options = [];
          }
          cb(this.options); // 回调函数，用于更新搜索建议
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val) {
      if (!val) return; // 如果没有选中任何项，则返回
      this.form = {
        // 更新位置信息
        lng: val.location.lng,
        lat: val.location.lat,
      };
      this.removeMarker(); // 移除旧的标记点
      this.setMapMarker(); // 设置新的标记点
    },
  },
  mounted() {
    this.findAll()
    this.countNum();
  },
};
</script>

<style scoped>
.container {
  margin-top: 10px;
  width: 1800px;
  height: 865px;
}
.sidebar {
  width: 20%;
  height: 90%;
  /* 定位 */
  position: absolute;
  top: 10%;
  right: 0;
}
.sidebar-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.icon-text {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.text {
  width: 120px;
  height: 50%;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  font-size: 30px;
}
</style>